<template>
  <div class="agent-container">
    <!-- 页面头部 -->
    <div class="header-section">
      <h1 class="main-title">🤖 智能体市场分析系统</h1>
      <p class="subtitle">基于AI的印尼新能源汽车市场深度分析平台</p>
    </div>

    <!-- 对话区域 -->
    <div class="chat-area">
      <!-- 消息列表 -->
      <div class="message-list" ref="messageList">
        <div
            v-for="(message, index) in messages"
            :key="index"
            :class="['message', message.type]"
        >
          <div class="message-content">
            <div class="message-header">
              <span class="sender">{{ message.type === 'user' ? '👤 用户' : '🤖 智能体' }}</span>
              <span class="timestamp">{{ message.timestamp }}</span>
            </div>

            <!-- 1. 显示普通文本 -->
            <div v-if="!message.component" class="message-text">{{ message.content }}</div>

            <!-- 2. 显示处理状态指示器 -->
            <div v-if="message.processing" class="processing-indicator">
              <div class="processing-title">🔄 智能体处理中...</div>
              <div class="progress-container">
                <div class="progress-bar">
                  <div
                      class="progress-fill"
                      :style="{ width: message.progress + '%' }"
                  ></div>
                </div>
                <div class="progress-text">{{ message.progress }}%</div>
              </div>

              <!-- 处理阶段 -->
              <div class="stages-container">
                <div
                    v-for="(stage, stageIndex) in processingStages"
                    :key="stageIndex"
                    :class="['stage-item', getStageStatus(stageIndex, message.progress)]"
                >
                  <div class="stage-icon">
                    <span v-if="getStageStatus(stageIndex, message.progress) === 'completed'">✓</span>
                    <span v-else-if="getStageStatus(stageIndex, message.progress) === 'active'">●</span>
                    <span v-else>{{ stageIndex + 1 }}</span>
                  </div>
                  <div class="stage-text">{{ stage }}</div>
                </div>
              </div>
            </div>

            <!-- 3. 动态渲染生成的报告组件 -->
            <div v-if="message.component" class="result-component-wrapper">
              <div class="results-title">✅ 分析完成 - 生成报告</div>
              <component :is="message.component"></component>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="input-section">
        <div class="input-container">
          <textarea
              v-model="inputMessage"
              placeholder="请输入您的市场分析任务指令..."
              class="message-input"
              rows="3"
              @keydown.enter.prevent="handleSendMessage"
              :disabled="isProcessing"
          ></textarea>
          <div class="input-actions">
            <button
                @click="clearChat"
                class="clear-btn"
                :disabled="isProcessing"
            >
              🗑️ 清空
            </button>
            <button
                @click="handleSendMessage"
                class="send-btn"
                :disabled="isProcessing || !inputMessage.trim()"
            >
              <span v-if="isProcessing">处理中...</span>
              <span v-else>🚀 发送</span>
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted, nextTick, markRaw } from 'vue';
// 1. 导入全部三个报告组件
import MarketAnalysisReport from '@/components/kouzi1.vue';
import CompetitorAnalysisReport from '@/components/kouzi2.vue';
import ProductDefinitionReport from '@/components/kouzi3.vue';

// --- 响应式状态 ---
const messages = ref([]);
const inputMessage = ref('');
const isProcessing = ref(false);
const messageList = ref(null);

// 2. 扩展预设任务列表
const predefinedTasks = [
  '搜索现有印尼新能源汽车市场，从地理、人口、行为、心理四维度量化印尼市场，形成细分市场潜力分析数据，以网页展示。',
  '爬取印尼市场 2024 年在售新能源/内燃车型数据，进行竞品分析，得出空白市场。',
  '结合营销岗的消费者画像及需求洞察报告，输出产品定义方案',
];
const processingStages = [ '数据搜索与收集', '市场数据分析', '竞品数据建模', '可视化报告生成', '网页输出' ];

// --- 辅助方法 (保持不变) ---
const getCurrentTime = () => new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
const getStageStatus = (stageIndex, progress) => { /* ... */ return 'pending';};
const scrollToBottom = async () => { await nextTick(); if (messageList.value) { messageList.value.scrollTop = messageList.value.scrollHeight; } };
const simulateProcessing = (messageIndex) => { return new Promise((resolve) => { let progress = 0; const totalDuration = Math.random() * 3000 + 5000; const intervalTime = 200; const steps = totalDuration / intervalTime; const increment = 100 / steps; const interval = setInterval(() => { progress += increment; if (progress > 100) progress = 100; messages.value[messageIndex].progress = Math.floor(progress); if (progress >= 100) { clearInterval(interval); messages.value[messageIndex].processing = false; resolve(); } }, intervalTime); }); };

// --- 3. 扩展核心交互逻辑 ---
const handleSendMessage = async () => {
  if (!inputMessage.value.trim() || isProcessing.value) return;

  isProcessing.value = true;
  const userTask = inputMessage.value;

  messages.value.push({ type: 'user', content: userTask, timestamp: getCurrentTime() });
  inputMessage.value = '';
  await scrollToBottom();

  const agentMessageIndex = messages.value.length;
  messages.value.push({ type: 'agent', content: '正在分析您的任务需求...', timestamp: getCurrentTime(), processing: true, progress: 0, component: null });
  await scrollToBottom();

  await simulateProcessing(agentMessageIndex);

  const agentMessage = messages.value[agentMessageIndex];
  agentMessage.content = '';

  // **根据用户任务，决定渲染哪个组件**
  if (userTask.includes('产品定义')) {
    agentMessage.component = markRaw(ProductDefinitionReport);
  } else if (userTask.includes('竞品分析') || userTask.includes('爬取')) {
    agentMessage.component = markRaw(CompetitorAnalysisReport);
  } else if (userTask.includes('细分市场') || userTask.includes('四维度')) {
    agentMessage.component = markRaw(MarketAnalysisReport);
  } else {
    agentMessage.content = '抱歉，我暂时无法理解这个任务。请尝试预设的指令。';
  }

  isProcessing.value = false;
  await scrollToBottom();

  // 自动填充下一个任务
  const currentTaskIndex = predefinedTasks.indexOf(userTask);
  if (currentTaskIndex > -1 && currentTaskIndex < predefinedTasks.length - 1) {
    setTimeout(() => {
      inputMessage.value = predefinedTasks[currentTaskIndex + 1];
    }, 1500);
  }
};

const clearChat = () => {
  if (isProcessing.value) return;
  messages.value = [];
  inputMessage.value = predefinedTasks[0];
};

onMounted(() => {
  inputMessage.value = predefinedTasks[0];
});
</script>

<style scoped>
.agent-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  display: flex;
  flex-direction: column;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.header-section {
  text-align: center;
  padding: 30px 20px;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}

.main-title {
  font-size: 2.5rem;
  font-weight: 700;
  color: #1a2b4e;
  margin-bottom: 10px;
}

.subtitle {
  color: #5a6a8a;
  font-size: 1.1rem;
  margin: 0;
}

.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
  padding: 0 20px;
  overflow: hidden;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 20px 10px;
  margin-bottom: 20px;
}

.message {
  margin-bottom: 20px;
  display: flex;
}

.message.user {
  justify-content: flex-end;
}

.message.agent {
  justify-content: flex-start;
}

.message-content {
  padding: 20px;
  border-radius: 15px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
}

.message.user .message-content {
  background: linear-gradient(45deg, #4a90e2, #50e3c2);
  color: white;
  margin-left: 20%;
  max-width: 80%;
}

.message.agent .message-content {
  background: #f8f9fa;
  color: #333;
  margin-right: 20%;
  width: 100%;
  max-width: 100%;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  font-size: 0.9rem;
}

.sender {
  font-weight: 600;
}

.timestamp {
  opacity: 0.7;
}

.message-text {
  line-height: 1.6;
  font-size: 1rem;
}

.processing-indicator {
  margin-top: 20px;
  padding: 20px;
  background: rgba(74, 144, 226, 0.05);
  border-radius: 10px;
  border: 1px solid rgba(74, 144, 226, 0.1);
}

.processing-title {
  font-weight: 600;
  color: #4a90e2;
  margin-bottom: 15px;
}

.progress-container {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 20px;
}

.progress-bar {
  flex: 1;
  height: 8px;
  background: rgba(74, 144, 226, 0.2);
  border-radius: 4px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(45deg, #4a90e2, #50e3c2);
  border-radius: 4px;
  transition: width 0.3s ease;
}

.progress-text {
  font-weight: 600;
  color: #4a90e2;
  min-width: 40px;
}

.stages-container {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.stage-item {
  display: flex;
  align-items: center;
  padding: 10px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.stage-item.pending {
  opacity: 0.6;
}

.stage-item.active {
  background: rgba(74, 144, 226, 0.1);
  transform: scale(1.02);
}

.stage-item.completed {
  background: rgba(80, 227, 194, 0.15);
}

.stage-icon {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  margin-right: 15px;
  font-size: 14px;
}

.stage-item.pending .stage-icon {
  background: #e0e0e0;
  color: #666;
}

.stage-item.active .stage-icon {
  background: #4a90e2;
  color: white;
}

.stage-item.completed .stage-icon {
  background: #50e3c2;
  color: white;
}

.result-component-wrapper {
  margin-top: 16px;
}

.results-title {
  font-size: 1.2rem;
  font-weight: 600;
  color: #333;
  margin-bottom: 16px;
  text-align: center;
}

.input-section {
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(10px);
  border-radius: 15px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  border-top: 1px solid white;
}

.input-container {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.message-input {
  width: 100%;
  padding: 15px;
  border: 1px solid #dcdfe6;
  border-radius: 10px;
  font-size: 1rem;
  resize: vertical;
  font-family: inherit;
  transition: all 0.3s ease;
}

.message-input:focus {
  outline: none;
  border-color: #4a90e2;
  box-shadow: 0 0 0 3px rgba(74, 144, 226, 0.1);
}

.input-actions {
  display: flex;
  gap: 15px;
  justify-content: flex-end;
}

.clear-btn, .send-btn {
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 1rem;
}

.clear-btn {
  background: #f8f9fa;
  color: #666;
  border: 1px solid #dcdfe6;
}

.clear-btn:hover:not(:disabled) {
  background: #e9ecef;
}

.send-btn {
  background: linear-gradient(45deg, #4a90e2, #50e3c2);
  color: white;
  min-width: 100px;
}

.send-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(74, 144, 226, 0.3);
}

.send-btn:disabled, .clear-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}
</style>